﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Common.Helper;
using Core.Extensions.Authorizations.Helpers;
using easyui.AuthHelper;
using easyui.Models;
using Filters.Models;
using GBLServices;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Model.ViewModels;

namespace easyui.Controllers
{
    [AllowAnonymous]
    public class LoginController : Controller
    {
        PermissionRequirement _permissionRequirement;
        MenuServices _Menu;
        public LoginController(PermissionRequirement permissionRequirement,MenuServices menu)
        {
            _permissionRequirement = permissionRequirement;
            _Menu = menu;
        }
        public IActionResult Login()
        {
            return View("../login");
        }

        [HttpPost]
        public  ObjectResult Submit([FromForm]LoginModel login)
        {
            TokenModelJwt tokenModel = new TokenModelJwt { Uid = 1, Role = "Admin" };
            var jwtStr = JwtHelper.IssueJwt(tokenModel);
            var suc = true;
            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }
        
        [HttpPost]
        [Route("jwttoken3.0")]//[FromForm]LoginModel login
        public async Task<IActionResult> GetJWTToken3(LoginModel login)
        {
            string jwtStr = string.Empty;
            
            if (login == null || string.IsNullOrEmpty(login.loginName) || string.IsNullOrEmpty(login.password))
            {
                
                var ret = new BaseResultModel(code: StatusCodes.Status404NotFound , 
                    message: "用户名或密码不能为空", returnStatus: ReturnStatus.Fail);
                
                return Ok(ret);
            }
            login.uid = "1";
            login.password = MD5Helper.MD5Encrypt32(login.password);

            var user = "系统管理员";
            if (user != null)
            {
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name,login.loginName),
                    new Claim(JwtRegisteredClaimNames.Jti, login.uid),
                    new Claim(ClaimTypes.Expiration,DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString())
                };
                claims.AddRange(user.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

                //连接数据库，获取用户权限名称
                var data = await _Menu.GetMenuAsync(int.Parse(login.uid));
                var list = (from item in data
                            where item.module != 0
                            select new PermissionItem
                            {
                                Role = item.rolename,
                                Url = item.path
                            }
                            ).ToList();

                _permissionRequirement.Permissions = list;
                _permissionRequirement.menus = data;

                //用户标识
                //var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                //identity.AddClaims(claims);

                var token = JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement);
                
                var ret = new BaseResultModel(code: 200, message: "获取成功", token);

                return Ok(ret);
            }
            else
            {
                var ret = new BaseResultModel(code: StatusCodes.Status204NoContent, message: "认证失败",returnStatus:ReturnStatus.Fail);
                return BadRequest(ret);
            }
            
        }

    }
}